package com.ptma.dao;

import java.io.Serializable;
import java.util.List;

import javax.persistence.PersistenceException;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import com.ptma.dao.i.IGenericDao;

@Primary
@Service
public class GenericDao<T extends Serializable, ID extends Serializable>
		implements IGenericDao<T, ID> {

	@Autowired
	private SessionFactory sessionFactory;

	public Session openSession() {
		return sessionFactory.openSession();
	}

	@SuppressWarnings("unchecked")
	public T save(ID objToSave) throws PersistenceException,
			ConstraintViolationException {

		return (T) openSession().save(objToSave);

	}

	@SuppressWarnings("unchecked")
	public List<T> findAllById(ID objtToFind) {
		return (List<T>) sessionFactory.openSession().get(
				objtToFind.getClass(), objtToFind);
	}

	@SuppressWarnings("unchecked")
	public T findById(ID objtToFind) {
		return (T) sessionFactory.openSession()
				.get(this.getClass(), objtToFind);
	}

	public boolean isExist(ID objToCheck) {
		return false;
	}

	public void saveOrUpdate(ID objToSave) throws PersistenceException,
			ConstraintViolationException {

		sessionFactory.openSession().saveOrUpdate(objToSave);
	}

	public void update(ID objToUpdate) throws PersistenceException {
		sessionFactory.openSession().update(objToUpdate);
	}

	public void delete(T objToDelete) throws PersistenceException,
			ConstraintViolationException {

		sessionFactory.openSession().delete(objToDelete);
	}
}
